<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :xs="24" :md="8">
        <el-card class="profile-card">
          <div class="profile-avatar">
            <el-avatar :size="100" :src="profileData.avatar">
              {{ profileData.username ? profileData.username.charAt(0).toUpperCase() : 'A' }}
            </el-avatar>
            <h3>{{ profileData.nickName || profileData.username }}</h3>
            <p class="role-tag">
              <el-tag type="success">{{ getRoleName(profileData.role) }}</el-tag>
            </p>
          </div>
          <el-divider />
          <div class="profile-info">
            <div class="info-item">
              <span class="label">账号：</span>
              <span class="value">{{ profileData.username }}</span>
            </div>
            <div class="info-item">
              <span class="label">邮箱：</span>
              <span class="value">{{ profileData.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机：</span>
              <span class="value">{{ profileData.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ profileData.createdAt }}</span>
            </div>
            <div class="info-item">
              <span class="label">最后登录：</span>
              <span class="value">{{ profileData.lastLoginTime }}</span>
            </div>
          </div>
        </el-card>

        <!-- 操作统计 -->
        <el-card class="stats-card" style="margin-top: 20px;">
          <template #header>
            <span>操作统计</span>
          </template>
          <div class="stats-list">
            <div class="stats-item">
              <el-icon color="#409eff" :size="24"><Document /></el-icon>
              <div class="stats-info">
                <div class="stats-value">{{ operationStats.todayCount || 0 }}</div>
                <div class="stats-label">今日操作</div>
              </div>
            </div>
            <el-divider />
            <div class="stats-item">
              <el-icon color="#67c23a" :size="24"><Checked /></el-icon>
              <div class="stats-info">
                <div class="stats-value">{{ operationStats.weekCount || 0 }}</div>
                <div class="stats-label">本周操作</div>
              </div>
            </div>
            <el-divider />
            <div class="stats-item">
              <el-icon color="#e6a23c" :size="24"><TrendCharts /></el-icon>
              <div class="stats-info">
                <div class="stats-value">{{ operationStats.totalCount || 0 }}</div>
                <div class="stats-label">总操作数</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧详细信息 -->
      <el-col :xs="24" :md="16">
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-card>
              <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="昵称" prop="nickName">
                  <el-input v-model="formData.nickName" placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="formData.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                  <el-input v-model="formData.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateProfile">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>

          <!-- 修改密码 -->
          <el-tab-pane label="修改密码" name="password">
            <el-card>
              <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                <el-form-item label="原密码" prop="oldPassword">
                  <el-input 
                    v-model="passwordForm.oldPassword" 
                    type="password" 
                    placeholder="请输入原密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input 
                    v-model="passwordForm.newPassword" 
                    type="password" 
                    placeholder="请输入新密码（至少8位）"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input 
                    v-model="passwordForm.confirmPassword" 
                    type="password" 
                    placeholder="请再次输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword">确认修改</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>

          <!-- 操作历史 -->
          <el-tab-pane label="操作历史" name="history">
            <el-card>
              <el-table :data="operationHistory" v-loading="historyLoading" stripe>
                <el-table-column prop="module" label="模块" width="100" />
                <el-table-column prop="type" label="操作类型" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getOperationType(row.type)">{{ row.type }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="detail" label="操作详情" show-overflow-tooltip />
                <el-table-column prop="createdAt" label="操作时间" width="180" />
              </el-table>
              <div style="display: flex; justify-content: flex-end; margin-top: 12px;">
                <el-pagination
                  :current-page="historyPage"
                  :page-size="10"
                  :total="historyTotal"
                  layout="total, prev, pager, next"
                  @current-change="handleHistoryPageChange"
                />
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Checked, TrendCharts } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/authStore'

const auth = useAuthStore()
const activeTab = ref('basic')

const profileData = ref({})
const operationStats = ref({})

const formRef = ref(null)
const formData = reactive({
  nickName: '',
  email: '',
  phone: ''
})

const rules = {
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码至少需要8位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

const operationHistory = ref([])
const historyLoading = ref(false)
const historyPage = ref(1)
const historyTotal = ref(0)

// 获取个人信息
const getProfile = async () => {
  try {
    const response = await request.get('/admin/auth/info')
    if (response.code === 0 && response.data) {
      profileData.value = response.data
      formData.nickName = response.data.nickName || ''
      formData.email = response.data.email || ''
      formData.phone = response.data.phone || ''
    }
  } catch (error) {
    ElMessage.error('获取个人信息失败')
  }
}

// 获取操作统计
const getOperationStats = async () => {
  try {
    const response = await request.get('/admin/profile/operation-stats')
    if (response.code === 0) {
      operationStats.value = response.data
    }
  } catch (error) {
    console.error('获取操作统计失败', error)
  }
}

// 获取操作历史
const getOperationHistory = async () => {
  historyLoading.value = true
  try {
    const response = await request.get('/admin/profile/operation-history', {
      params: {
        page: historyPage.value,
        pageSize: 10
      }
    })
    if (response.code === 0) {
      operationHistory.value = response.data.list
      historyTotal.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取操作历史失败')
  } finally {
    historyLoading.value = false
  }
}

// 更新个人信息
const updateProfile = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request.put('/admin/profile/update', formData)
        if (response.code === 0) {
          ElMessage.success('个人信息更新成功')
          getProfile()
        }
      } catch (error) {
        ElMessage.error('个人信息更新失败')
      }
    }
  })
}

// 修改密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request.put('/admin/profile/change-password', {
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        if (response.code === 0) {
          ElMessage.success('密码修改成功，请重新登录')
          // 清除登录信息，跳转到登录页
          setTimeout(() => {
            auth.logoutAdmin()
            location.href = '/admin/login'
          }, 1500)
        }
      } catch (error) {
        ElMessage.error('密码修改失败')
      }
    }
  })
}

// 操作历史分页
const handleHistoryPageChange = (page) => {
  historyPage.value = page
  getOperationHistory()
}

// 获取角色名称
const getRoleName = (role) => {
  const map = {
    superadmin: '超级管理员',
    admin: '管理员',
    operator: '运营人员'
  }
  return map[role] || '管理员'
}

// 获取操作类型样式
const getOperationType = (type) => {
  const map = {
    'CREATE': 'success',
    'UPDATE': 'primary',
    'DELETE': 'danger',
    'VIEW': 'info'
  }
  return map[type] || ''
}

onMounted(() => {
  getProfile()
  getOperationStats()
  getOperationHistory()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  text-align: center;
}

.profile-avatar {
  padding: 20px 0;
}

.profile-avatar h3 {
  margin: 16px 0 8px;
  font-size: 20px;
  font-weight: 600;
}

.role-tag {
  margin: 0;
}

.profile-info {
  text-align: left;
}

.info-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  font-weight: 600;
  color: #666;
  min-width: 90px;
}

.info-item .value {
  color: #333;
  flex: 1;
}

.stats-card {
  margin-top: 20px;
}

.stats-list {
  padding: 10px 0;
}

.stats-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stats-label {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style>
